package com.ggs.rg.ybjb.usermodule.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ggs.rg.ybjb.pojomodule.pojo.*;
import com.ggs.rg.ybjb.pojomodule.util.CommonUtil;
import com.ggs.rg.ybjb.pojomodule.util.StringTools;
import com.ggs.rg.ybjb.pojomodule.util.constants.ErrorEnum;
import com.ggs.rg.ybjb.usermodule.exception.OrderException;
import com.ggs.rg.ybjb.usermodule.service.*;
import com.ggs.rg.ybjb.usermodule.util.ImageUtil;
import com.ggs.rg.ybjb.usermodule.util.ListPagesUitl;
import com.ggs.rg.ybjb.usermodule.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


@RestController
@RequestMapping("/shopping")
public class TGoodsShoppingController {

    @Autowired
    TGoodsShoppingService tGoodsShoppingService;

    @Autowired
    TShoppingService tShoppingService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    MaterService materService;

    @Autowired
    UserService userService;

    @Autowired
    TOrderService tOrderService;

    @Autowired
    TGoodsOrderService tGoodsOrderService;

    @Autowired
    RedisUtil redisUtil;


    //把商品加入购物车
    @PostMapping("/addShopping")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject addShopping(@RequestBody JSONObject jsonObject) {
        Integer pid = jsonObject.getInteger("pid");
        Integer count = jsonObject.getInteger("count");
        String phone = jsonObject.getString("phone");
        //判断用户表内是否存在用户
        List<String> users = new ArrayList<>();
        List<TUser> userList = userService.list();
        for (TUser tu : userList) {
            String phone1 = tu.getPhone();
            users.add(phone1);
        }
        if (users.contains(phone)) {
            //先遍历购物车表查询是否是新用户
            QueryWrapper<TShopping> tShoppingQueryWrapper = new QueryWrapper<>();
            QueryWrapper<TShopping> phone1 = tShoppingQueryWrapper.select("phone");
            List<TShopping> list = tShoppingService.list(phone1);
            List<String> phoneList = new ArrayList<>();
            if (!(StringTools.isNullOrEmpty(pid) ||
                    StringTools.isNullOrEmpty(count))) {
                for (TShopping ts1 : list) {
                    String phone2 = ts1.getPhone();
                    phoneList.add(phone2);
                }
                if (phoneList.contains(phone)) {
                    QueryWrapper<TShopping> queryWrapper1 = new QueryWrapper<>();
                    QueryWrapper<TShopping> select = queryWrapper1.eq("phone", phone).select("sid");
                    List<TShopping> list1 = tShoppingService.list(select);
                    for (TShopping ts : list1) {
                        Integer sid = ts.getSid();
                        if (!count.equals(0)) {
                            TGoodsShopping tGoodsShopping = new TGoodsShopping(pid, count, sid);
                            tGoodsShoppingService.save(tGoodsShopping);

                        } else {
                            return CommonUtil.sqlErrorJson("请输入商品数量！");
                        }
                    }
                } else {
                    TShopping tShopping = new TShopping(phone);
                    tShoppingService.save(tShopping);
                    Integer sid = tShopping.getSid();
                    if (!(StringTools.isNullOrEmpty(pid) ||
                            StringTools.isNullOrEmpty(count))) {
                        if (!count.equals(0)) {
                            TGoodsShopping tGoodsShopping = new TGoodsShopping(pid, count, sid);
                            tGoodsShoppingService.save(tGoodsShopping);
                            return CommonUtil.successJson();
                        } else {
                            return CommonUtil.sqlErrorJson("请输入商品数量！");
                        }
                    } else {
                        return CommonUtil.sqlErrorJson("请输入完整的数据！");
                    }
                }
            } else {
                return CommonUtil.sqlErrorJson("请输入完整的数据");
            }
            return CommonUtil.successJson();
        } else {
            return CommonUtil.sqlErrorJson("用户不存在");
        }
    }

    //查询购物车 分页显示
    @GetMapping("/selectShopping")
    public JSONObject selectShopping(@RequestParam("phone") String phone,
                                     @RequestParam("pagesNumber") Integer pagesNumber){
        //分页页码默认显示1
        Integer SID = 0;
        if (StringTools.isNullOrEmpty(pagesNumber)){
            pagesNumber = 1;
        }else if (pagesNumber <= 0){
            pagesNumber = 1;
        }
        List<String> userPhone = new ArrayList<>();
        List<TUser> userList = userService.list();
        for (TUser tu : userList){
            String phone1 = tu.getPhone();
            userPhone.add(phone1);
        }
        if (userPhone.contains(phone)){
            QueryWrapper<TShopping> queryWrapper = new QueryWrapper<>();
            QueryWrapper<TShopping> select = queryWrapper.eq("phone", phone).select("sid");
            List<TShopping> list = tShoppingService.list(select);
            List<Map<String,Object>> mapList = new ArrayList<>();
            for (TShopping ts : list){
                Integer sid = ts.getSid();
                SID = sid;
                QueryWrapper<TGoodsShopping> queryWrapper1 = new QueryWrapper<>();
                QueryWrapper<TGoodsShopping> select1 = queryWrapper1.eq("sid", sid);
                List<TGoodsShopping> list1 = tGoodsShoppingService.list(select1);
                for (TGoodsShopping tgs : list1){
                    Map<String,Object> map = new TreeMap<>();
                    Integer count = tgs.getCount();
                    Integer pid = tgs.getPid();
                    Mater mater = materService.getById(pid);
                    String text = mater.getText();
                    Double price = mater.getPrice();
                    int gid = mater.getGid();
                    Goods goods = goodsService.getById(gid);
                    String name = goods.getName();
                    String image = goods.getImage();
                    String imageAddr = ImageUtil.getImageAddr(image, "9001");
                    Integer id = tgs.getId();
                    map.put("id",id);
                    map.put("name",name);
                    map.put("image",imageAddr);
                    map.put("pid",pid);
                    map.put("text",text);
                    map.put("price",price);
                    map.put("count",count);
                    map.put("sid",sid);
                    mapList.add(map);
                }
            }
            Map<String, Object> map = ListPagesUitl.listPaging(mapList, pagesNumber, 5);
            map.put("sid",SID);
            return CommonUtil.successJson(map);
        }else {
            return CommonUtil.sqlErrorJson("用户不存在");
        }
    }

    //删除购物车
    @PostMapping("/deleteShopping")
    public JSONObject deleteShopping(@RequestBody JSONObject jsonObject){
        JSONArray array = jsonObject.getJSONArray("id");
        String phone = jsonObject.getString("phone");
        //转换JSONArray为List
        List<Integer> listId = JSONObject.parseArray(array.toString(),Integer.class);
        //根据用户电话号码查询用户的购物车id
        QueryWrapper<TShopping> queryWrapper = new QueryWrapper<>();
        QueryWrapper<TShopping> select = queryWrapper.eq("phone", phone).select("sid");
        TShopping tShopping = tShoppingService.getOne(select);
        Integer sid = tShopping.getSid();
        //根据用户购物车id查询购物车信息，并判断是否包含传入的删除id
        QueryWrapper<TGoodsShopping> queryWrapper1 = new QueryWrapper<>();
        QueryWrapper<TGoodsShopping> select1 = queryWrapper1.eq("sid", sid);
        List<TGoodsShopping> list = tGoodsShoppingService.list(select1);
        List<Integer> listId1 = new ArrayList<>();
        for (TGoodsShopping tgs : list){
            Integer id = tgs.getId();
            listId1.add(id);
        }
        if (listId.isEmpty()){
            return CommonUtil.sqlErrorJson("没有选择删除商品");
        }else {
            //判断查询的所有购物车id是否包含传入的所有id
            if (listId1.containsAll(listId)){
                for (Integer integer : listId){
                    tGoodsShoppingService.removeById(integer);
                }
                return CommonUtil.successJson();
            }else {
                return CommonUtil.sqlErrorJson("删除的商品不存在购物车内");
            }
        }
    }

    //购物车生成订单
    @PostMapping("/addOrderByShopping")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject addOrderByShopping(@RequestBody JSONObject params) throws Exception {
        if (StringTools.isNullOrEmpty(params))
            return CommonUtil.errorJson(ErrorEnum.E_90003);
        CommonUtil.hasAllRequired(params,"sid,ids");
        Integer sid = params.getInteger("sid");
        TShopping shopping = tShoppingService.getById(sid);
        if (StringTools.isNullOrEmpty(shopping))
            return CommonUtil.sqlErrorJson("sid为:" + sid + "的购物车不存在");
        //用来保存购物车商品关系表中的数据
        List<JSONObject> goodsInfos = new ArrayList();
        //用来保存订单总价
        Double orderPrice = 0d;
        JSONArray ids = params.getJSONArray("ids");
        //由于用户可能同时点击购物车中多个商品进行订单的生成,所以需要遍历
        //并将遍历后得到的pid,count放到一个json中，再将这个json放到list集合中
        //后面生成订单与订单参数表时需要用到
        for (int i = 0 ; i < ids.size() ; i++){
            Integer id = ids.getInteger(i);
            TGoodsShopping tGoodsShopping = tGoodsShoppingService.getById(id);
            if (StringTools.isNullOrEmpty(tGoodsShopping)){
                throw new Exception("查询不到id为:" + id + "的关系表数据");
            }
            Integer pid = tGoodsShopping.getPid();
            Integer count = tGoodsShopping.getCount();
            Mater mater = materService.getById(pid);
            Double price = mater.getPrice();
            orderPrice += price * count ;
            JSONObject goodInfo = new JSONObject();
            goodInfo.put("pid",pid);
            goodInfo.put("count",count);
            goodsInfos.add(goodInfo);
        }
//        if (goodsInfos.size() < 0)
//            return CommonUtil.errorJson("500","购物车中没有商品!");
        //程序执行到这,说明参数一切正常,开始生成订单
        TOrder order = new TOrder(shopping.getPhone(),orderPrice);
        boolean addOrderResult = tOrderService.save(order);
        if (addOrderResult){
            //遍历用户购买的所有商品参数
            for (int i = 0 ; i < goodsInfos.size() ; i++){
                JSONObject goodInfo = goodsInfos.get(i);
                Integer pid = goodInfo.getInteger("pid");
                Integer count = goodInfo.getInteger("count");
                String oid = order.getOid();
                TGoodsOrder tGoodsOrder = new TGoodsOrder(oid,pid,count);
                boolean addResult = tGoodsOrderService.save(tGoodsOrder);
                if (!addResult)
                    throw new OrderException("插入订单商品关系表失败,订商品号为:"+ pid + ",订单号为:"+oid+"!");
            }
            //向redis缓存中放入一个标志,用来标志订单未付款,30分钟如果还没付款,则这个标志过期,删除数据库该订单记录
            //设置标志10s后过期
            redisUtil.set("orderStatus."+order.getOid(),0,60*30);
            //程序执行到这里,说明订单生成成功,接下来需要将购物车中生成了订单的商品清空
            for (int i = 0 ; i < ids.size() ; i++){
                Integer id = ids.getInteger(i);
                boolean result = tGoodsShoppingService.removeById(id);
                if (!result)
                    throw new Exception("删除购物车商品关系表中id为:" + id + "的数据失败");
            }
            return CommonUtil.successJson(order.getOid());
        }else{
            return CommonUtil.sqlErrorJson("生成订单失败!!!");
        }
    }
}
